﻿/*
 * Catalyst - http://catalystobjects.com
 * 
 * New BSD License (BSD)
 * 
 * Copyright (c) 2009, Ashley Brener
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
 * 
 * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
 * 
 * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
 * 
 * Neither the name of Midlet Earth nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Caching;
using Catalyst.Caching;
using SubSonic;

namespace Catalyst
{
	public abstract class BusinessObjectList<ItemType, ListType> : ActiveList<ItemType, ListType>, IBusinessObjectList, IDataRelational
		where ItemType : BusinessObject<ItemType>, new()
		where ListType : BusinessObjectList<ItemType, ListType>, new()
	{
		public void LoadAsRelation<T>(TableSchema.Table RelatedTableSchema, string ForeignKeyName, object PrimaryKeyValue, HashSet<Aggregate> Aggregates)
		{
			BaseSchema = RelatedTableSchema;
		
			bool loadFromCache = false;

			if (HttpContext.Current != null)
			{
				HashSet<string> cacheEnabledTables = new HashSet<string>(SqlCacheDependencyAdmin.GetTablesEnabledForNotifications(BaseSchema.Provider.DefaultConnectionString));
				foreach (string enabledTable in cacheEnabledTables)
				{
					if (enabledTable == BaseSchema.TableName)
					{
						loadFromCache = true;
						break;
					}
				}
			}

			if (loadFromCache)
			{
				ListType allCached = new ListType().LoadAll(RelatedTableSchema);

				foreach (ItemType item in allCached)
				{
					object obj = item.GetColumnValue(ForeignKeyName);

					if (item.GetColumnValue(ForeignKeyName).Equals(PrimaryKeyValue))
					{
						Add(item);
					}
				}
			}
			else
			{
				SqlQuery query = new Select()
				.From(BaseSchema)
				.Where(ForeignKeyName).IsEqualTo(PrimaryKeyValue);

				if (Aggregates != null && Aggregates.Count > 0)
				{
					foreach (Aggregate aggregate in Aggregates)
					{
						query.And(aggregate);
					}
				}
				
				LoadAndCloseReader(RelatedTableSchema, query.ExecuteReader());
			}

			//return (T)Convert.ChangeType(this, GetType());
		}

		#region IDataRelational Members

		public abstract TableSchema.Table GetTableSchema();

		public void LoadAsRelation(TableSchema.Table RelatedTableSchema, string ForeignKeyName, object PrimaryKeyValue, HashSet<Aggregate> Aggregates)
		{
			LoadAsRelation<IDataRelational>(RelatedTableSchema, ForeignKeyName, PrimaryKeyValue, Aggregates);
		}

		public void LoadRelations(IList<string> RelationNames)
		{
			if (Items != null && Items.Count > 0 && RelationNames != null && RelationNames.Count > 0)
			{
				//relationNamesToLoad = new List<string>(RelationNames);
				
				foreach (ItemType businessObject in Items)
				{
					businessObject.LoadRelations(RelationNames);
				}
			}
		}

		#endregion

		private static readonly object _lockBaseSchema = new object();

		protected internal static TableSchema.Table table;

		/// <summary>
		/// The base static class that holds all schema info for the table.
		/// The class must be instanced at least once to populate this table.
		/// </summary>
		protected internal static TableSchema.Table BaseSchema
		{
			get
			{
				if (table == null)
				{
					lock (_lockBaseSchema)
						new ListType();
				}
				return table;
			}
			set { table = value; }
		}

		//private Dictionary<string, OrderByDirection> cacheCollectionOrderBys;

		//private string getAllCacheKey()
		//{
		//    return String.Format("{0}_All{1}", table.Provider.Name, table.Name);
		//}

		//private List<T> getAllItems<T>() where T : ItemType, new()
		//{
		//    SqlQuery query = new Select().From(table);

		//    if (cacheCollectionOrderBys != null && cacheCollectionOrderBys.Count > 0)
		//    {
		//        foreach (var orderBy in cacheCollectionOrderBys)
		//        {
		//            switch (orderBy.Value)
		//            {
		//                case OrderByDirection.Desc: query.OrderDesc(orderBy.Key); break;
		//                default: query.OrderAsc(orderBy.Key); break;
		//            }
		//        }
		//    }

		//    IDataReader reader = null;

		//    List<T> list = new List<T>();

		//    using (reader = query.ExecuteReader())
		//    {
		//        ItemType businessObject = null;

		//        while (reader.Read())
		//        {
		//                businessObject = new ItemType();
		//                businessObject.Load(BaseSchema, reader);
		//                list.Add((T)businessObject);
		//        }
		//    }

		//    return list;
		//}

		//private CacheSettings<List<T>> getAllCachedListItems<T>() where T : ItemType, new()
		//{
		//    CacheSettings<List<T>> settings = new CacheSettings<List<T>>();

		//    SqlCacheDependency dependency = null;

		//    if (HttpContext.Current != null)
		//    {
		//        HashSet<string> cacheEnabledTables = new HashSet<string>(SqlCacheDependencyAdmin.GetTablesEnabledForNotifications(table.Provider.DefaultConnectionString));
		//        foreach (string enabledTable in cacheEnabledTables)
		//        {
		//            if (enabledTable == table.TableName)
		//            {
		//                dependency = new SqlCacheDependency(table.Provider.Name, enabledTable);
		//                break;
		//            }
		//        }
		//    }

		//    settings.CachedObject = getAllItems<T>();
		//    settings.Dependency = dependency;

		//    return settings;
		//}

		public ListType LoadAll<T>(Dictionary<string, OrderByDirection> OrderBys) where T : ItemType, new()
		{
			return LoadAll<T>(GetTableSchema(), OrderBys);
		}

		public ListType LoadAll<T>(TableSchema.Table TableSchema) where T : ItemType, new()
		{
			return LoadAll<T>(TableSchema, null);
		}

		public ListType LoadAll<T>(TableSchema.Table TableSchema, Dictionary<string, OrderByDirection> OrderBys) where T : ItemType, new()
		{
			BaseSchema = TableSchema;

			//cacheCollectionOrderBys = OrderBys;

			//bool loadFromCache = false;

			//if (HttpContext.Current != null)
			//{
			//    HashSet<string> cacheEnabledTables = new HashSet<string>(SqlCacheDependencyAdmin.GetTablesEnabledForNotifications(BaseSchema.Provider.DefaultConnectionString));
			//    foreach (string enabledTable in cacheEnabledTables)
			//    {
			//        if (enabledTable == BaseSchema.TableName)
			//        {
			//            loadFromCache = true;
			//            break;
			//        }
			//    }
			//}

			//List<ItemType> itemsToLoad = null;

			//if (loadFromCache)
			//{
			//    List<T> allItems = CachingService.GetCachedObject(getAllCacheKey(), new CachingService.ObjectLoader<List<T>>(getAllCachedListItems<T>));

			//    itemsToLoad = Cloning.CloneHelper<List<ItemType>>.Clone(new List<ItemType>(allItems.Cast<ItemType>()));

			//}
			//else
			//{
			//    itemsToLoad = new List<ItemType>(getAllItems<T>().Cast<ItemType>());
			//}

			//AddRange(itemsToLoad);

			//DataTable allData = CacheHelper.GetCachedData(new CacheHelper.DataRequest(BaseSchema, OrderBys));

			List<T> allItems = CachedDataLoader.GetCachedList<T>(new CachedDataLoader.DataRequest(BaseSchema, OrderBys));

			List<ItemType> itemsToLoad = new List<ItemType>(allItems.Cast<ItemType>());

			AddRange(itemsToLoad);

			return (ListType)this;
		}

		public ListType LoadAll<T>() where T : ItemType, new()
		{
			return LoadAll<T>(GetTableSchema());
		}

		public virtual ListType LoadAll(Dictionary<string, OrderByDirection> OrderBys)
		{
			return LoadAll<ItemType>(GetTableSchema(), OrderBys);
		}

		public virtual ListType LoadAll(TableSchema.Table TableSchema, Dictionary<string, OrderByDirection> OrderBys)
		{
			return LoadAll<ItemType>(TableSchema, OrderBys);
		}

		public virtual ListType LoadAll()
		{
			return LoadAll<ItemType>();
		}

		public virtual ListType LoadAll(TableSchema.Table TableSchema)
		{
			return LoadAll<ItemType>(TableSchema);
		}

		public void ClearCache()
		{
			//LoadSchema();

			BaseSchema = GetTableSchema();

			HttpContext.Current.Cache.Remove(CachedDataLoader.GetCacheKey(BaseSchema));
		}

		public ListType ReloadAll()
		{
			return ReloadAll<ItemType>();
		}

		public ListType ReloadAll<T>() where T : ItemType, new()
		{
			ClearCache();

			return LoadAll<T>();
		}

		public void Load(ListType List)
		{
			Load(List.ToArray());
		}

		public void Load(IEnumerable<ItemType> collection)
		{
			foreach (ItemType item in collection)
			{
				this.Add(item);
			}

			//return (ListType)this;
		}

		public virtual void LoadAndCloseReader(IDataReader Reader)
		{
			LoadAndCloseReader<ItemType>(GetTableSchema(), Reader);
		}

		public virtual void LoadAndCloseReader<T>(IDataReader Reader) where T : ItemType, new()
		{
			LoadAndCloseReader<T>(GetTableSchema(), Reader);
		}

		public void LoadAndCloseReader(TableSchema.Table ViewSchema, IDataReader Reader)
		{
			LoadAndCloseReader<ItemType>(ViewSchema, Reader);
		}

		protected internal void LoadAndCloseReader<T>(TableSchema.Table ViewSchema, IDataReader Reader) where T : ItemType, new()
		{
			try
			{
				Load<T>(ViewSchema, Reader);
			}
			finally
			{
				if (Reader != null)
				{
					Reader.Close();
				}
			}
		}

		public virtual void Load(IDataReader Reader)
		{
			Load<ItemType>(GetTableSchema(), Reader);
		}

		public virtual void Load<T>(IDataReader Reader) where T : ItemType, new()
		{
			Load<T>(GetTableSchema(), Reader);
		}

		public void Load(TableSchema.Table ViewSchema, IDataReader Reader)
		{
			Load<ItemType>(ViewSchema, Reader);
		}

		protected internal void Load<T>(TableSchema.Table ViewSchema, IDataReader Reader) where T : ItemType, new()
		{
			T businessObject = null;

			//loadSchema(ViewName);

			BaseSchema = ViewSchema;

			Dictionary<string, object> fields = null;

			while (Reader.Read())
			{
				try
				{
					fields = new Dictionary<string, object>();

					for (int i = 0; i < Reader.FieldCount; i++)
					{
						fields.Add(Reader.GetName(i), Reader[i]);
					}

					businessObject = new T();

					businessObject.Load(BaseSchema, fields);

					//businessObject.Load(Reader);

					Add(businessObject);
				}
				catch
				{
					throw new Exception(Reader.GetName(0));
				}
			}

			//isLoaded = true;

			//return (ListType)this;
		}

		//public override ListType Load(DataTable DataTable)
		//{
		//    return Load(GetTableSchema(), DataTable);
		//}

		public void Load(DataTable DataTable)
		{
			Load(GetTableSchema(), DataTable);
		}

		public void Load(TableSchema.Table TableSchema, DataTable DataTable)
		{
			//ItemType businessObject = null;

			//loadSchema(ViewName);
			BaseSchema = TableSchema;

			//foreach (DataRow row in DataTable.Rows)
			//{
			//    businessObject = new ItemType();
			//    businessObject.Load(row);
			//    Add(businessObject);
			//}

			//isLoaded = true;

			ItemType businessObject = null;

			foreach (DataRow row in DataTable.Rows)
			{
				businessObject = new ItemType();
				businessObject.Load(BaseSchema, row);
				Add(businessObject);
			}

			//return (ListType)this;
		}

		/// <summary>
		/// Returns BusinessObjectList as foreign from a cache
		/// </summary>
		/// <param name="ForeignKeyName"></param>
		/// <param name="PrimaryKeyValue"></param>
		/// <returns></returns>
		//public ListType LoadAsForeign(string ForeignKeyName, object PrimaryKeyValue)
		//{
		//    ListType abstractObjects = new ListType();
		//    abstractObjects.LoadAll();

		//    foreach (ItemType item in abstractObjects)
		//    {
		//        if (item.GetDataValue(ForeignKeyName).Equals(PrimaryKeyValue))
		//        {
		//            Add(item);
		//        }
		//    }

		//    return (ListType)this;
		//}

		

		//#region *** Relations ***

		//public void LoadRelations()
		//{
		//    if (Items != null && Items.Count > 0)
		//    {
		//        foreach (ItemType businessObject in Items)
		//        {
		//            businessObject.LoadRelations();
		//        }
		//    }
		//}

		

		//#endregion

		public virtual void Save()
		{
			Save(String.Empty);
		}

		public virtual void Save(int userID)
		{
			Save(userID.ToString());
		}

		public virtual void Save(Guid userID)
		{
			string sUserID = userID.ToString();
			Save(sUserID);
		}

		public virtual void Save(string userName)
		{
			foreach (ItemType businessObject in this)
			{
				businessObject.Save(userName);
			}
		}

		#region IBusinessObjectList Members


		

		#endregion
	}
}
